package com.foton.bpc.all.remoting.netty.handler;

import com.foton.bpc.all.remoting.dto.Response;
import com.foton.bpc.all.remoting.netty.adpect.HandlerAdpect;
import com.foton.bpc.all.remoting.netty.channel.BpcChannel;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author RenPu
 * @Date 2023/6/13 11:12
 * @Version 1.0
 * @Description:      服务调用端-- 响应结果处理器
 **/
public class BpcClientHandler implements HandlerAdpect {


   public final static ConcurrentHashMap<Long, CompletableFuture>  concurrentHashMap=new ConcurrentHashMap<>();


    //服务调用端-- 结果处理器


    /**
     * 收到数据，就是接收到响应结果，也就是一个方法得返回值
     * @param bpcChannel
     * @param msg
     * @throws Exception
     */
    @Override
    public void onRecevice(BpcChannel bpcChannel, Object msg) throws Exception {
        Response response=(Response)msg;
        concurrentHashMap.get(response.getRequestId()).complete(response);

    }

    @Override
    public void onWrite(BpcChannel bpcChannel, Object msg) {

    }


    /**
     * 登记一下，给每一个等待的线程，创建返回一个单独的future
     *结合唯一标识，进行请求与对象和响应的对象进行对应识别，避免混乱
     * concurrentHashMap作为中间缓存介质
     * 使用CompletableFuture，实现跨线程进行通信机制
     * @param uniqueId
     * @return
     */
    public static CompletableFuture withResult(long uniqueId){
        CompletableFuture future = new CompletableFuture();
        concurrentHashMap.put(uniqueId,future);
        return future;
    }
}
